<?php
/**
 * @uses       Custom_Db_Table_Abstract
 * @license    Ritesh Jha (mailrkj@gmail.com)
 */

class Custom_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
	protected $_userId = '';

	protected $_roleId = '';

	protected $_error = '';

	protected $_orderField = 'id';

	protected $_orderType = 'ASC';

	/**
	 * Paginator instance
	 * @var object
	 */
	protected $_paginator = '';

	/**
	 * For paginator
	 * @var int
	 */
	protected $_recordsPerPage = '10';

	/**
	 * For paginator
	 * @var int
	 */
	protected $_pageNo = '1';

	/**
	 * Contains logger object for db-table
	 * @var object
	 */
	protected $_logger = '';
	

	public function init()
	{
		$auth = Zend_Auth::getInstance();
		
		if($auth->hasIdentity())
		{
			$this->_roleId =  $auth->getIdentity()->role_id;
			$this->_userId =  $auth->getIdentity()->id;
            $this->_bankId =  $auth->getIdentity()->bank_id;
		}

		$this->_logger =  Zend_Registry::get('logger');
	}

	/**
	 * Inser data into table
	 * @param array $data
	 * @return bool specially inserted id, if success
	 */
	public function insert($data)
	{
		try
		{
			if(in_array('created',$this->info(self::COLS))) $data['created'] = date('Y-m-d H:i:s');
			
			return parent::insert($data);
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
		}
	}

	/**
	 * Update record by where cluse
	 * @param array $data
	 * @param string $where sql condition
	 * @return bool
	 */
	public function update($data, $where)
	{
		try
		{
			if(in_array('modified',$this->info(self::COLS))) $data['modified'] = date('Y-m-d H:i:s');

			return parent::update($data, $where);
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
		}
	}

	/**
	 * update record by id
	 * @param array $data
	 * @param int $id
	 * @return bool
	 */
	public function updateById($data, $id)
	{
		$where = "id = " . $id;
		return $this->update($data,$where);
	}

	/**
	 * Update table by foreign key
	 * @param array $data data to update
	 * @param string $name table field name
	 * @param string $value field value
	 * @return bool
	 */
	public function updateByColumn($data, $name, $value)
	{
		$where = $name." = " . $value;
		return $this->update($data,$where);
	}

	/**
	 * Set order by
	 * @param string $field db field for order by default id
	 * @param string $type order type default ASC
	 */
	public function setOrderBy($field, $type = 'ASC')
	{
		$this->_orderField = $field;
		$this->_orderType  = strtoupper($type);
	}

	/**
	 * Get order by field and type
	 * @return array
	 */
	public function getOrderBy()
	{
		return $this->_orderField." ".$this->_orderType;
	}

	/**
	 * Get data by different id
	 * @param mixed $ids  array or id seprated by comma
	 * @return array
	 */
	public function get($ids)
	{
		try
		{
			if($ids)
			{
				if(is_array($ids))
				{
					return $this->find($ids)->toArray();
				}
				else
				{
					return $this->find(explode(',',$ids))->toArray();
				}
			}
			else
			{
				return false;
			}
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

	}

	/**
	 * Get single row by id
	 * @param int $id
	 * @parm array $fields
	 * @return return array
	 */
	public function getOne($id,  $fields = '*')
	{
		try
		{
			return $this->getOneByColumn('id',$id,  $fields);
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

	}

	/**
	 * Get all data
	 * @param array $fields selected fields
	 * @return array
	 */
	public function getAll($searchKey = '', $fields = '*')
	{
		try
		{
			#if search key
			if($searchKey)
			{
				$where = '';
				foreach($this->info(self::COLS) as $field) $where .= $field." like '".$searchKey."%' OR ";
				$where = substr_replace($where, '', -3);
			}
			else
			{
				$where = '1=1';
			}

			$select = $this->select()
							->from($this->_name,$fields)
							->where($where)
							->order($this->getOrderBy());
			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
		
	}
	
	/**
	 * Fetch data by field name
	 * @param string $name table field name
	 * @param string $value field value
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getByColumn($name, $value, $fields = '*')
	{
		try
		{
			$select = $this->select()
							->from($this->_name, $fields)
							->where($name.' = ?', $value)
							->order($this->getOrderBy());
			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}

	/**
	 * Fetch data by more than one field name
	 * @param string $params (field name and value associate array)
	 * array('field1'=> 'value1', 'field2' => 'value2')
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getByColumns($params, $fields = '*')
	{
		try
		{
			$select = $this->select()
							->from($this->_name, $fields);
			foreach($params as $field => $value)
			{
				$select->where($field ."= ?", $value);
			}
				$select->order($this->getOrderBy());
			
			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}
	
	/**
	 * Fetch single data based on column name
	 * @param string $name
	 * @param string $value
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getOneByColumn($name, $value, $fields = '*')
	{
		try
		{
			$row = $this->fetchRow($this->select()
										->from($this->_name, $fields)
										->where($name.'= ?', $value));
			if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}


	/**
	 * Fetch single data by more than one field name
	 * @param string $params (field name and value associate array)
	 * array('field1'=> 'value1', 'field2' => 'value2')
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getOneByColumns($params, $fields = '*')
	{
		try
		{
			$select = $this->select()
							->from($this->_name, $fields);
			foreach($params as $field => $value)
			{
				$select->where($field ."= ?", $value);
			}
				$select->order($this->getOrderBy());

			$row = $this->fetchRow($select);
			if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}


	/**
	 * Set model level error message
	 * @param mixed $error
	 */
	public function setError($error)
	{
		$this->_error =  $error;
	}

	/**
	 * Get model level error message
	 * @return mixed
	 */
	public function getError()
	{
		return $this->_error;
	}

	/**
	 * Set pagination parameter
	 * @param int $recordsPerPage
	 * @param int $currentPage
	 */
	public function setPaginator($recordsPerPage, $currentPage)
	{
		$this->_pageNo = $currentPage;
		$this->_recordsPerPage = $recordsPerPage;
	}

	/**
	 * Get paginator instance
	 * @return object
	 */
	public function getPaginator()
	{
		return $this->_paginator;
	}

	/**
	 *
	 * @param <type> $select
	 * @return <type>
	 */
	protected function _applyPaginator($select)
	{
		$paginator = Zend_Paginator::factory($select);
		$paginator->setItemCountPerPage($this->_recordsPerPage);
		$paginator->setCurrentPageNumber($this->_pageNo);

		$this->_paginator = $paginator;
		
		return $paginator->getCurrentItems();
	}

	/**
	 * Delete table tow by foreign key value
	 * @param string $name table field name
	 * @param string $value field value
	 * @return bool
	 */
	public function deleteByColumn($name, $value)
	{
		$where = $name." = " . $value;
		return $this->delete($where);
	}

	/**
	 * Delete by primary key field id
	 * @param string $id 
	 * @return bool
	 */
	public function deleteById($id)
	{
		$where = "id = " . $id;
		return $this->delete($where);
	}

	/**
	 * fetch all user data with user details
	 * @param int $id (primary key of user assets)
	 * @param array $fields array of fields to show
	 * @return array
	 */
	public function  fetchAllByUser( $user_id = null, $searchColumns = array(),
                                    $searchKey = null, $fields = "*")
	{

		$objUser = new User_Model_DbTable_User();
	
		try
		{
			$select = $this->select()
							->setIntegrityCheck(false)
							->from(array('master' => $this->_name), array($fields))
							->join(array('user' => $objUser->_name), 'user.id = master.user_id', array('role_id as user.role_id', 'first_name as user.first_name',
																										'last_name as user.last_name', 'email as user.email'));
							
            if($user_id)
                $select->where("master.user_id = ?", $user_id);
            else if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
                $select->where("1 = ?", "1");
            else
                $select->where("master.user_id = ?", $this->_userId);

            #search condition
            if($searchKey && count($searchColumns) > 0)
            {
                $cond = '';
                $where .= ' and (';
                foreach($searchColumns as $field) $cond .= $field." like '".$searchKey."%' OR ";
                $where .= substr_replace($cond, '', -3);
                $where .= ')';
            }
            $select->where("?", $where);
            #order by
            $select->order($this->getOrderBy());

			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}

    /**
	 * fetch single user data with user details
	 * @param int $id (primary key of user assets)
	 * @param array $fields array of fields to show
	 * @return array
	 */
	public function  fetchOneByUser( $id , $user_id = null,  $fields = "*")
	{
		$objUser = new User_Model_DbTable_User();
             
        try
		{
            $select = $this->select()
                        ->setIntegrityCheck(false)
                        ->from(array('master' => $this->_name), array($fields))
                        ->join(array('user' => $objUser->_name), 'user.id = master.user_id', array('role_id as user.role_id', 'first_name as user.first_name',
                                                                                        'last_name as user.last_name', 'email as user.email'));
                      
			if($user_id)
            {
                $select->where("master.id = ?", $id);
                $select->where("master.user_id = ?", $user_id);
            }
            else if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
            {
                $select->where("master.id = ?", $id);
            }
            else
            {
                $select->where("master.id = ?", $id);
                $select->where("master.user_id = ?", $this->_userId);
            }

            $row = $this->fetchRow($select);
            
            if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}
}

?>
